﻿//* We are given an array of integers and a number S. 
//Write a program to find if there exists a subset of the elements of the array that has a sum S. Example:
//	arr={2, 1, 2, 4, 3, 5, 2, 6}, S=14  yes (1+2+5+6)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _16SubsetSum
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Array size:");
            string strArraySize = Console.ReadLine();
            int arraySize = int.Parse(strArraySize);
            int[] array = new int[arraySize];
            for (int i = 0; i <= array.Length - 1; i++)
            {
                Console.Write("array[{0}]:", i);
                string strElement = Console.ReadLine();
                array[i] = int.Parse(strElement);
            }
            Console.WriteLine("The array looks like this:");
            foreach (var item in array)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.Write("What sum are we looking for:");
            string strS = Console.ReadLine();
            int s = int.Parse(strS);
            Console.WriteLine("-------------------------------------------------------");
            int maxSubSets = (int)Math.Pow(2, array.Length);
            int checkSum = 0;
            string elements = "";
            for (int i = 1; i < maxSubSets; i++)
            {
                elements = "";
                checkSum = 0;
                for (int j = 0; j <= array.Length - 1; j++)
                {
                    int mask = 1 << j;
                    int andMask = i & mask;
                    int bit = andMask >> j;
                    if (bit == 1)
                    {
                        checkSum += array[j];
                        elements += " " + array[j];
                    }
                }
                if (checkSum == s)
                {
                    Console.WriteLine("{0} Yes: ({1})", s, elements);
                }
            }
        }
    }
}
